package cn.muqingfeng.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import cn.muqingfeng.api.to.UserTO;
import cn.muqingfeng.bbs.constants.Constants;

import com.google.gson.Gson;

public class AccountManager {
	private static final String FILE_NAME = "_am.xml";

	public static final boolean isLogin(Context context) {
		SharedPreferences preference = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		return !TextUtils.isEmpty(preference.getString(Constants.KEY_USER, null));
	}

	public static final UserTO getUser(Context context) {
		SharedPreferences preference = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		String userStr = preference.getString(Constants.KEY_USER, null);
		UserTO userTO = null;
		try {
			if (!TextUtils.isEmpty(userStr)) {
				userTO = new UserTO();
				String key = context.getPackageName();
				String str = new Blowfish(key).decryptString(userStr);
				Gson gson = new Gson();
				userTO = gson.fromJson(str, UserTO.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return userTO;
	}

	public static final void saveUser(Context context, UserTO userTO) {
		SharedPreferences preference = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		Gson gson = new Gson();
		String userStr = gson.toJson(userTO);
		String key = context.getPackageName();
		String result = new Blowfish(key).encryptString(userStr);
		Editor editor = preference.edit();
		editor.putString(Constants.KEY_USER, result);
		editor.commit();
	}

	public static final void clear(Context context) {
		SharedPreferences preference = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		preference.edit().clear().commit();
	}

	public static final String getPassword(Context context) {
		SharedPreferences preference = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		String key = context.getPackageName();
		String sCipherText = preference.getString(Constants.KEY_PASSWORD, null);
		if (!TextUtils.isEmpty(sCipherText)) {
			return new Blowfish(key).decryptString(sCipherText);
		}
		return null;
	}

	public static final void setPassword(Context context, String password) {
		SharedPreferences preference = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		String key = context.getPackageName();
		String sCipherText = new Blowfish(key).encryptString(password);
		Editor editor = preference.edit();
		editor.putString(Constants.KEY_PASSWORD, sCipherText);
		editor.commit();
	}
}
